//
//  PARemitMoneyView.m
//  PAMobileWallet
//
//  Created by Pay_SMP002 on 13-7-4.
//  Copyright (c) 2013年 平安付. All rights reserved.
//

#import "PARemitMoneyView.h"
#import "PARemitMoneyViewController.h"
#import "UIColor+Extend.h"
#import "VoiceConverter.h"
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>


@interface PARemitMoneyView()

@end

@implementation PARemitMoneyView
@synthesize firstTopView;
@synthesize paytoLable;
@synthesize paytoContactTF;
@synthesize addContactBT;

@synthesize havetradeTopView;
@synthesize payMoneyLable;
@synthesize sendMoneyLable;

@synthesize payView;
@synthesize starVoiceBT;
@synthesize contextTF;
@synthesize starPayBT;

@synthesize paypassView;
@synthesize backVoiceBT;
@synthesize contextpassTF;
@synthesize starPaypassBT;

@synthesize historyTradeTAB;
@synthesize recordVoiceBTN;
@synthesize recordVoiceBgIV;
@synthesize commentLAB;

@synthesize recorder;
@synthesize player;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        CGSize size = frame.size;
        CGSize viewHright = CGSizeMake(320, 90/2);

        firstTopView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, viewHright.width, viewHright.height)];
        firstTopView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pay_tfbgImge2.png"]];
        [self addSubview:firstTopView];
        
        paytoLable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 60, viewHright.height)];
        paytoLable.textColor = [UIColor grayColor];
        paytoLable.text = @"付款给:";
        paytoLable.textAlignment = NSTextAlignmentLeft;
        paytoLable.backgroundColor = [UIColor clearColor];
        [firstTopView addSubview:paytoLable];
        
        paytoContactTF = [[UITextField alloc] initWithFrame:CGRectMake(5+60, 0, 180, viewHright.height)];
        paytoContactTF.textColor = [UIColor darkTextColor];
        [paytoContactTF setBorderStyle:UITextBorderStyleNone]; //外框类型
        paytoContactTF.keyboardType = UIKeyboardTypeNumberPad;
        paytoContactTF.placeholder = @"转账对方手机号"; //默认显示的字
//#warning 调试用
//        paytoContactTF.text = @"13764947399";
        paytoContactTF.secureTextEntry = NO; //密码
        paytoContactTF.delegate = self.parentController;
        paytoContactTF.contentHorizontalAlignment = NSTextAlignmentCenter;
        paytoContactTF.contentVerticalAlignment = NSTextAlignmentLeft;
        paytoContactTF.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
        [paytoContactTF setTextColor:[UIColor darkTextColor]];
        paytoContactTF.backgroundColor = [UIColor clearColor];
        [firstTopView addSubview:paytoContactTF];
        [paytoContactTF addTarget:self.parentController action:@selector(targetPhoneEndEdit:) forControlEvents:UIControlEventEditingDidEnd];

        addContactBT = [UIButton buttonWithType:UIButtonTypeCustom];
        addContactBT.backgroundColor = [UIColor clearColor];
        [addContactBT setBackgroundImage:[UIImage imageNamed:@"pay_addContact.png"] forState:UIControlStateNormal];
        addContactBT.frame = CGRectMake(size.width-70/2-10,5,70/2,70/2);
        addContactBT.tag = 1;
        [addContactBT addTarget:self action:@selector(buttonActive:) forControlEvents:UIControlEventTouchUpInside];
        [firstTopView addSubview:addContactBT];

        [self addSubview:firstTopView];
        firstTopView.hidden = NO;
        
        havetradeTopView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, viewHright.width, viewHright.height)];
        havetradeTopView.backgroundColor = [UIColor whiteColor];
        [self addSubview:firstTopView];
        
        for (int i = 0; i < 2; i ++){
            UIButton * payAndSendBT = [UIButton buttonWithType:UIButtonTypeCustom];
            payAndSendBT.userInteractionEnabled = NO;
            payAndSendBT.backgroundColor = [UIColor clearColor];
            
            if (i == 0)
            {
                [payAndSendBT setBackgroundImage:[UIImage imageNamed:@"pay_recive.png"] forState:UIControlStateNormal];
                payAndSendBT.frame = CGRectMake(5,13/2,32,32);
            }
            if (i == 1)
            {
                [payAndSendBT setBackgroundImage:[UIImage imageNamed:@"pay_send.png"] forState:UIControlStateNormal];
                payAndSendBT.frame = CGRectMake(size.width - 100 - 64/2 - 6,13/2,32,32);
            }
            [havetradeTopView addSubview:payAndSendBT];
        }
        
        payMoneyLable = [[UILabel alloc] initWithFrame:CGRectMake(5+64/2+6, 0, 100, viewHright.height)];
        payMoneyLable.textColor = [UIColor darkTextColor];
        payMoneyLable.text = @"";
        payMoneyLable.textAlignment = NSTextAlignmentLeft;
        payMoneyLable.backgroundColor = [UIColor clearColor];
        [havetradeTopView addSubview:payMoneyLable];
        
        sendMoneyLable = [[UILabel alloc] initWithFrame:CGRectMake(size.width - 100, 0, 100, viewHright.height)];
        sendMoneyLable.textColor = [UIColor darkTextColor];
        sendMoneyLable.text = @"";
        sendMoneyLable.textAlignment = NSTextAlignmentLeft;
        sendMoneyLable.backgroundColor = [UIColor clearColor];
        [havetradeTopView addSubview:sendMoneyLable];

        [self addSubview:havetradeTopView];
        havetradeTopView.hidden = YES;
        
        payView = [[UIView alloc] initWithFrame:CGRectMake(0, (iPhone5?568:480) - 216 - 112/2 -20, 640/2, 112/2)];
        payView.backgroundColor = [UIColor clearColor];
        UIImageView * payImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 640/2, 112/2)];
        payImageView.image = [UIImage imageNamed:@"pay_enter.png"];
        [payView addSubview:payImageView];
        
        starVoiceBT = [UIButton buttonWithType:UIButtonTypeCustom];
        starVoiceBT.backgroundColor = [UIColor clearColor];
        [starVoiceBT setBackgroundImage:[UIImage imageNamed:@"pay_voiceStar.png"] forState:UIControlStateNormal];
        starVoiceBT.tag = 2;
        starVoiceBT.frame = CGRectMake(10,10+(82-56)/2,38/2,56/2);
        [starVoiceBT addTarget:self action:@selector(voiceStartAction:) forControlEvents:UIControlEventTouchUpInside];
        [payView addSubview:starVoiceBT];

        contextTF = [[UITextField alloc] initWithFrame:CGRectMake(5+38/2+26,20,400/2,58/2)];
        [contextTF setBorderStyle:UITextBorderStyleNone]; //外框类型
        contextTF.keyboardType = UIKeyboardTypeDecimalPad;
        contextTF.placeholder = @"请输入金额"; //默认显示的字
        contextTF.secureTextEntry = NO; //密码
//#warning 调试用
//        contextTF.text = @"1";
        contextTF.delegate = self.parentController;
        contextTF.contentHorizontalAlignment = NSTextAlignmentCenter;
        contextTF.contentVerticalAlignment = NSTextAlignmentLeft;
        contextTF.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
        [contextTF setTextColor:[UIColor colorWithHexString:@"#ACB086"]];
        [contextTF addTarget:self action:@selector(checkcontextTF:) forControlEvents:UIControlEventEditingChanged];
        [payView addSubview:contextTF];

        starPayBT = [UIButton buttonWithType:UIButtonTypeCustom];
        starPayBT.frame = CGRectMake(size.width - 130/2 - 5,13 + (82-68)/2, 130/2, 68/2);
        starPayBT.backgroundColor = [UIColor clearColor];
        [starPayBT setBackgroundImage:[UIImage imageNamed:@"确定01.png"] forState:UIControlStateNormal];
        [starPayBT addTarget:self action:@selector(changeState:) forControlEvents:UIControlEventTouchUpInside];
        starPayBT.enabled = NO;
        starPayBT.selected = NO;
        [payView addSubview:starPayBT];

        [self addSubview:payView];
        
        paypassView = [[UIView alloc] initWithFrame:CGRectMake(320, (iPhone5?568:480) - 216 - 112/2 -20, 640/2, 112/2)];
        paypassView.backgroundColor = [UIColor clearColor];
        UIImageView * paypassImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 640/2, 112/2)];
        paypassImageView.image = [UIImage imageNamed:@"pay_enter.png"];
        [paypassView addSubview:paypassImageView];
        
        backVoiceBT = [UIButton buttonWithType:UIButtonTypeCustom];
        backVoiceBT.backgroundColor = [UIColor clearColor];
        [backVoiceBT setBackgroundImage:[UIImage imageNamed:@"pay_back.png"] forState:UIControlStateNormal];
        backVoiceBT.frame = CGRectMake(10,7+(82-41)/2,26/2,41/2);
        [backVoiceBT addTarget:self action:@selector(changeState:) forControlEvents:UIControlEventTouchUpInside];
        [paypassView addSubview:backVoiceBT];
        
        contextpassTF = [[UITextField alloc] initWithFrame:CGRectMake(5+38/2+26,20,400/2,58/2)];
        [contextpassTF setBorderStyle:UITextBorderStyleNone]; //外框类型
        contextpassTF.keyboardType = UIKeyboardTypeASCIICapable;
        contextpassTF.returnKeyType = UIReturnKeyDone;
        contextpassTF.placeholder = @"请输入支付密码"; //默认显示的字
        contextpassTF.secureTextEntry = YES; //密码
//#warning 调试用
//        contextpassTF.text = @"123456";
        contextpassTF.delegate = self.parentController;
        contextpassTF.contentHorizontalAlignment = NSTextAlignmentCenter;
        contextpassTF.contentVerticalAlignment = NSTextAlignmentLeft;
        contextpassTF.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
        [contextpassTF setTextColor:[UIColor colorWithHexString:@"#ACB086"]];
        [contextpassTF addTarget:self action:@selector(checkcontextpassTF:) forControlEvents:UIControlEventEditingChanged];
        [paypassView addSubview:contextpassTF];
        
        starPaypassBT = [UIButton buttonWithType:UIButtonTypeCustom];
        starPaypassBT.frame = CGRectMake(size.width - 130/2 - 5,13 + (82-68)/2, 130/2, 68/2);
        starPaypassBT.backgroundColor = [UIColor clearColor];
        [starPaypassBT setBackgroundImage:[UIImage imageNamed:@"pay_payBT1.png"] forState:UIControlStateNormal];
        [starPaypassBT addTarget:self action:@selector(buttonActive:) forControlEvents:UIControlEventTouchUpInside];
        starPaypassBT.selected = NO;
        starPaypassBT.enabled = NO;
        starPaypassBT.tag = 3;
        [paypassView addSubview:starPaypassBT];
        [self addSubview:paypassView];
        
        self.historyTradeTAB = [[UITableView alloc] initWithFrame:CGRectMake(0, 44 + 45, 320, (iPhone5?548:460) - 216 - 112/2 - 44 - 45 + 10)];
        self.historyTradeTAB.separatorStyle = NO;
        self.historyTradeTAB.dataSource = self.parentController;
        self.historyTradeTAB.delegate = self.parentController;
        [self addSubview:self.historyTradeTAB];
        
        recordVoiceBgIV = [[UIImageView alloc] initWithFrame:CGRectMake(0, (iPhone5?548:460) - 432/2, 320, 432/2)];
        recordVoiceBgIV.image = [UIImage imageNamed:@"voice_record-back.png"];
        [self addSubview:recordVoiceBgIV];
        
        recordVoiceBTN = [[UIButton alloc] initWithFrame:CGRectMake((320 - (243/2))/2, (iPhone5?568:480) - 432/2 + 5, 243/2, 244/2)];
        [recordVoiceBTN setImage:[UIImage imageNamed:@"voice_record.png"] forState:UIControlStateNormal];
        [recordVoiceBTN setImage:[UIImage imageNamed:@"voice_recording.png"] forState:UIControlStateHighlighted];
        [recordVoiceBTN addTarget:self action:@selector(starAudio:) forControlEvents:UIControlEventTouchDown];
        recordVoiceBTN.tag = 100;
        [recordVoiceBTN addTarget:self action:@selector(stopAudio:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:recordVoiceBTN];
        
        CGRect rect = recordVoiceBTN.frame;
        rect.origin.y += rect.size.height + 10;
        rect.size.height = 24;
        commentLAB.font = [UIFont systemFontOfSize:18.0];
        commentLAB = [[UILabel alloc] initWithFrame:rect];
        commentLAB.backgroundColor = [UIColor clearColor];
        commentLAB.textColor = [UIColor colorWithHexString:@"#acb0b6"];
        [commentLAB setTextAlignment:NSTextAlignmentCenter];
        commentLAB.text = @"录入付款理由";
        [self addSubview:commentLAB];
        
        [self audio];
    }
    return self;
}

- (void)checkcontextTF:(id)sender
{
    if ([contextTF.text length]>0) {
        starPayBT.enabled = YES;
        [starPayBT setBackgroundImage:[UIImage imageNamed:@"确定02.png"] forState:UIControlStateNormal];
        [starPayBT setBackgroundImage:[UIImage imageNamed:@"确定03.png"] forState:UIControlStateHighlighted];
    }else{
        starPayBT.enabled = NO;
        [starPayBT setBackgroundImage:[UIImage imageNamed:@"确定01.png"] forState:UIControlStateNormal];
    }
}

- (void)checkcontextpassTF:(id)sender
{
    if ([contextpassTF.text length]>0) {
        starPaypassBT.enabled = YES;
        [starPaypassBT setBackgroundImage:[UIImage imageNamed:@"pay_payBT2.png"] forState:UIControlStateNormal];
        [starPaypassBT setBackgroundImage:[UIImage imageNamed:@"pay_payBT2.png"] forState:UIControlStateHighlighted];
    }else{
        starPaypassBT.enabled = NO;
        [starPaypassBT setBackgroundImage:[UIImage imageNamed:@"pay_payBT1.png"] forState:UIControlStateNormal];
    }
}

-(void)buttonActive:(id)sender
{
    [self.parentController testNext:sender];
}

- (void)starAudio:(id)sender
{
    [starVoiceBT setBackgroundImage:[UIImage imageNamed:@"pay_voiceStaring.png"] forState:UIControlStateNormal];
    commentLAB.text = @"松开结束";

    NSFileManager * fileManager=[NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:[DocumentsPath stringByAppendingPathComponent:@"mediaComment.wav"]])
    {
        [fileManager removeItemAtPath:[DocumentsPath stringByAppendingPathComponent:@"mediaComment.wav"] error:nil];
    }
    
    int tag = [(UIButton *)sender tag];
    if (tag == 100) {
        //创建录音文件，准备录音
        if ([self.recorder prepareToRecord]) {
            //开始
            [self.recorder record];
        }
    }
}

- (void)stopAudio:(id)sender {
    [starVoiceBT setBackgroundImage:[UIImage imageNamed:@"pay_voiceStaring.png"] forState:UIControlStateNormal];
    commentLAB.text = @"录音结束";

    [self.recorder deleteRecording];
    [self.recorder stop];

    [VoiceConverter wavToAmr:[DocumentsPath stringByAppendingPathComponent:@"mediaComment.wav"]
                 amrSavePath:[DocumentsPath stringByAppendingPathComponent:@"mediaComment.amr"]];
}

- (void)audio
{
    //录音设置
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                          [NSNumber numberWithFloat: 8000.0],AVSampleRateKey, //采样率
                                          [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                                          [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,//采样位数 默认 16
                                          [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,//通道的数目
                                          //                                   [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,//大端还是小端 是内存的组织方式
                                          //                                   [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,//采样信号是整数还是浮点数
                                          [NSNumber numberWithInt: AVAudioQualityMedium],AVEncoderAudioQualityKey,//音频编码质量
                                          nil];


    NSURL *url = [NSURL fileURLWithPath:[DocumentsPath stringByAppendingPathComponent:@"mediaComment.wav"]];

    NSError *error;
    //初始化
    self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&error];
    //开启音量检测
    self.recorder.meteringEnabled = YES;
    self.recorder.delegate = self;
}

- (void)voiceStartAction:(id)sender
{
    [self.contextpassTF resignFirstResponder];

    if (self.parentController && [self.parentController respondsToSelector:@selector(voiceStartAction:)]) {
        [self.parentController performSelector:@selector(voiceStartAction:) withObject:sender];
    }
}

- (BOOL) checkPayAmount:(NSString**) pMsg
{
    NSString* payAmount = contextTF.text;
    NSString* msg = @"";
    
    if([payAmount length] == 0)
    {
        *pMsg = @"金额不能为空";
        return FALSE;
    }
    
    NSError* error = nil;
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(([0-9]*\\.[0-9]+)|([0-9]+))$" options:nil error:&error];
    
    int matchCnt = [regex numberOfMatchesInString:payAmount options:nil range:NSMakeRange(0, payAmount.length)];
    
    if(matchCnt == 0)
    {
        *pMsg = @"无效的金额";
        return FALSE;
    }
    
    return TRUE;
    
}

- (void)changeState:(UIButton *)sender
{
    if (sender == starPayBT)
    {
        [self.contextpassTF becomeFirstResponder];
        
        NSString* msg = nil;
        

        if ([self checkPayAmount:&msg])
        {
            //[self startAnimition:paypassView];

            if (self.parentController && [self.parentController respondsToSelector:@selector(payStartAction:)])
            {
                [self.parentController performSelector:@selector(payStartAction:) withObject:sender];
            }
        }
        else
        {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
    }
    
    if (sender == backVoiceBT)
    {
        [self.contextTF becomeFirstResponder];
        [self startAnimition:payView];
    }
}

- (void)startAnimition:(UIView *)sender
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve: UIViewAnimationCurveLinear];
    [UIView setAnimationDuration:0.1];
    [UIView setAnimationDelegate:self];
    
    CGRect payViewRect = payView.frame;
    CGRect paypassViewRect = paypassView.frame;
    if (sender == paypassView)
    {
        paypassViewRect.origin.x = 0;
        payViewRect.origin.x = -320;
    }
    if (sender == payView)
    {
        paypassViewRect.origin.x = 320;
        payViewRect.origin.x = 0;
    }
    payView.frame = payViewRect;
    paypassView.frame = paypassViewRect;
    [self.contextTF becomeFirstResponder];
    [UIView commitAnimations];
}

@end
